//引入公共函数
var util = require('../../utils/util');

//存放页面实例的变量
var that;

//请求域名的URL
var requestDomain = util.config('requestDomain');

Page({
  data: {
    year: 2017,
    month: 1,
    withdrawCashList: [],
    finding: false,
    maxDate: '',
    withdrawCashTotal: 0,
    withdrawCashing: false,
    notSetBankCardInfo: true,
    bankCardInfo: {
        bankCardRealName: '设置提现银行卡',
        bankCardNumber: '**** **** **** **** ****'
    }
  },

  onLoad:function(){
    
    that = this;

    let date = new Date();

    that.setData({
      maxDate: date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate(),
      year: date.getFullYear(),
      month: date.getMonth() + 1
    });

    that.getWithdrawCashOrders();

  },

  onShow: function() {
    let {storeData} = util.globalData('loginData');
    let {storeBankCardInfo} = storeData;
    if (storeBankCardInfo.bankCardRealName && storeBankCardInfo.bankCardNumber && storeBankCardInfo.bankCardRealName != '' && storeBankCardInfo.bankCardNumber != '') {
        that.setData({ notSetBankCardInfo: false });
        that.setData({
            bankCardInfo: {
                bankCardRealName: storeBankCardInfo.bankCardRealName,
                bankCardNumber: '**** **** **** **** ' + storeBankCardInfo.bankCardNumber.substr(storeBankCardInfo.bankCardNumber.length - 4, 4)
            }
        });  
    }
    else {
        wx.showModal({
            title: '系统提示',
            content: '您还未设置提现的银行卡，设置提现银行卡后，提现的资金将从粿团平台转账到您的银行卡',
            cancelText: '稍后再来',
            confirmText: '立即设置',
            confirmColor: '#f06759',
            success: function(modal) {
                if(modal.confirm) {
                    that.goBankCardSetting();
                }
            }
        })
    }
  },

  getWithdrawCashOrders: function() {

    wx.showNavigationBarLoading();

    wx.showToast({
      title: '查询订单中',
      icon: 'loading',
      mask: true,
      duration: 10000
    });

    let {year, month} = that.data;

    that.setData({finding: true});

    wx.request({
      url: requestDomain + 'withdrawCash/find',

      data: {

        storeId: util.globalData('storeId'),

        _3rdSession: util.globalData('_3rdSession'),

        year: parseInt(year),

        month: parseInt(month)
        
      },
      
      method: 'POST',

      success: function(result){
        
        if(util.checkSuccess(result)) {

          let {data} = result.data;

          let withdrawCashList = [];

          console.log(data);

          for(let orderIndex in data) {

            let date = new Date(data[orderIndex].timestamp * 1000);

            let dateStr = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();

            let {withdrawCashId, storeReceiveMoney} = data[orderIndex];

            let found = false;

            for(let index in withdrawCashList) {
              if(withdrawCashList[index].date == dateStr) {
                withdrawCashList[index].orderIdList.push(data[orderIndex].orderId);
                for(let goodsIndex in data[orderIndex].goodsList) {
                    console.log(data[orderIndex].goodsList[goodsIndex].foodPrice || data[orderIndex].goodsList[goodsIndex].goodsPrice);
                    withdrawCashList[index].total += data[orderIndex].goodsList[goodsIndex].foodPrice || data[orderIndex].goodsList[goodsIndex].goodsPrice;
                }
                if (!data[orderIndex].orderDone) {
                    withdrawCashList[index].allowWithdrawCash = false;
                }
                found = true;
                break;
              }
            }

            if(!found) {
              let total = 0;
              for(let goodsIndex in data[orderIndex].goodsList) {
                total += data[orderIndex].goodsList[goodsIndex].foodPrice || data[orderIndex].goodsList[goodsIndex].goodsPrice;
              }
              withdrawCashList.push({
                orderIdList: [data[orderIndex].orderId],
                date: dateStr,
                total: total,
                withdrawCashId: withdrawCashId,
                storeReceiveMoney: storeReceiveMoney,
                allowWithdrawCash: data[orderIndex].orderDone
              }); 
            }
          }

          withdrawCashList.sort(function(a, b) {
            return new Date(b.date).getDate() - new Date(a.date).getDate();
          });

          for(let i in withdrawCashList) {
              console.log(withdrawCashList[i].total);
            if(withdrawCashList[i].total > 99) {
                withdrawCashList[i].total = ((withdrawCashList[i].total - (withdrawCashList[i].total * 0.02).toFixed(2)).toFixed(2) / 100).toFixed(2);
            }
            else {
                withdrawCashList[i].total = withdrawCashList[i].total / 100;
            }
          }

          console.log(withdrawCashList);

          that.setData({withdrawCashList, withdrawCashList});

          that.updateWithdrawCashTotal();

          wx.hideToast();

          wx.hideNavigationBarLoading();

          that.setData({ finding: false });

          wx.stopPullDownRefresh();

        }
        else {

           wx.hideToast();

           wx.hideNavigationBarLoading();

           that.setData({ finding: false });

           util.showError('查询失败', '系统在查询可提现订单时出现错误' + result.data.errMsg, result.data.errCode);

           wx.stopPullDownRefresh();

        }

      },
      fail: function(err) {
        
        console.log(err);

        wx.hideToast();

        wx.hideNavigationBarLoading();

        util.showError('查询失败', '发起查询订单请求失败');

        that.setData({finding: false});

        wx.stopPullDownRefresh();

      }
    })
  },

  dateChange: function(e) {
    let date = e.detail.value.split('-');
    that.setData({
      year: parseInt(date[0]),
      month: parseInt(date[1])
    });
    that.getWithdrawCashOrders();
  },

  updateWithdrawCashTotal: function() {

    let {withdrawCashList} = that.data;

    let {withdrawCashTotal} = that.data;

    withdrawCashTotal = 0;

    for(let index in withdrawCashList) {

        if (!withdrawCashList[index].allowWithdrawCash || withdrawCashList[index].storeReceiveMoney || withdrawCashList[index].withdrawCashId != '') {
        continue;
      }
      withdrawCashTotal += withdrawCashList[index].total * 100;

    }

    that.setData({withdrawCashTotal: withdrawCashTotal});

  },

  goBankCardSetting: function() {
    wx.navigateTo({
        url: '../bankCardSetting/bankCardSetting',
        fail: function() {
            wx.showModal({
                title: '跳转失败',
                content: '跳转到提现银行卡设置页面失败',
            });
        }
    });
  },

  goWithdrawCashDetail: function(e) {
    let {date, withdrawcashid} = e.currentTarget.dataset;
    if(withdrawcashid == '') {
      return;
    }
    wx.navigateTo({
      url: '../withdrawCashDetail/withdrawCashDetail?withdrawCashId=' + withdrawcashid + '&date=' + date,
      fail: function(err) {
        console.log(err);
        util.showError('错误', '跳转到提现详情失败');
      }
    })
  },

  withdrawCash: function() {
    let {year, month, withdrawCashList, withdrawCashTotal, notSetBankCardInfo} = that.data;
    if (notSetBankCardInfo) {
        wx.showModal({
            title: '提示',
            content: '您还未设置银行卡信息，请先点击上方设置银行卡信息',
        });
        return;
    }
    wx.showModal({
      title: '确认提现',
      content: '您将提现' + month + '月份的所有日结可提现金额，共' + (withdrawCashTotal / 100) + '元，是否需要提现？',
      success: function(modal) {
        if(modal.confirm) {

          wx.showNavigationBarLoading();

          that.setData({withdrawCashing: true});

          let withdrawCashOrderList = [];

          for(let index in withdrawCashList) {
            if(withdrawCashList[index].storeReceiveMoney || withdrawCashList[index].withdrawCashId != '') {
              continue;
            }
            for(let orderIndex in withdrawCashList[index].orderIdList) {
              withdrawCashOrderList.push(withdrawCashList[index].orderIdList[orderIndex]);
            }
          }

          console.log(withdrawCashOrderList);
          
          wx.request({

            url: requestDomain + 'withdrawCash/target',

            data: {

              storeId: util.globalData('storeId'),
              
              _3rdSession: util.globalData('_3rdSession'),

              withdrawCashOrderList: withdrawCashOrderList,

              withdrawCashTotal: withdrawCashTotal

            },

            method: 'POST',

            success: function(result){

              wx.hideNavigationBarLoading();

              that.setData({withdrawCashing: false});

              if(util.checkSuccess(result) && result.data && result.data.data) {
                
                console.log(result.data.data);
                that.getWithdrawCashOrders();

              }
              else {
                util.showError('操作失败', '系统在处理提现请求时发生了错误' + result.data.errMsg, result.data.errCode);
              }
            },

            fail: function(err) {

              wx.hideNavigationBarLoading();

              that.setData({withdrawCashing: false});

              util.showError('操作失败', '发起提现请求失败');

            }
          });
        }
      }
    });
  },

  onPullDownRefresh: function() {
      that.getWithdrawCashOrders();
  }

})